<template>
  <div class="p-4">
    <Timeline>
      <TimelineItem v-for="(item, index) in list" :key="index" style="min-height: 50px">
        <template #dot>
          <div style="border-radius: 50%" v-if="item.type == 'handle'">
            <img :src="item.userPhoto" style="width: 29px; height: 29px" />
          </div>
          <div
            style="width: 10px; height: 10px; background-color: #cccccc; border-radius: 50%"
            v-else-if="item.type == 'reply' || item.type == 'sendCopy' || item.type == 'connector'"
          ></div>
        </template>
        <div class="flex">
          <!-- <div>
            <Tag v-if="item.type == 'handle'" color="cyan">处理</Tag>
            <Tag v-else-if="item.type == 'reply'" color="blue">回复</Tag>
            <Tag v-else-if="item.type == 'sendCopy'" color="orange">抄送</Tag>
            <Tag v-else-if="item.type == 'connector'" color="purple">连接器</Tag>
          </div> -->

          <div class="flex-1">
            <div>
              <div class="flex">
                <template v-if="item.type == 'handle'">
                  {{ item.title }}
                </template>
                <template v-else-if="item.type == 'reply'">
                  <span style="color: #00000080; margin-right: 5px">{{ item.realName }}</span>
                  添加了回复
                </template>
                <template v-else-if="item.type == 'sendCopy'">
                  <span style="color: #00000080">{{ item.realName }} </span>
                  抄送给
                </template>
                <template v-if="item.type == 'connector'">
                  连接器 {{ item.title }} : {{ item.connectionActionName }}
                </template>
                <span style="margin-left: 5px; color: #ed6f6f" v-if="!item.time">待处理</span>
                <span style="color: #00000073; margin-left: 8px">{{ item.time }}</span>
                <div
                  v-if="item.type == 'handle' && item.time2"
                  style="
                    background-color: #f2f7ff;
                    border-radius: 999px;
                    padding: 0 8px;
                    margin-left: 5px;
                    display: flex;
                    align-items: center;
                    color: #418bff;
                  "
                >
                  <ClockCircleOutlined style="margin-right: 5px; color: #418bff" />
                  {{ item.showTimes }}
                </div>
              </div>
              <div>
                <template v-if="item.type == 'handle'">
                  <div v-if="item.privRealName && item.realName">
                    <span style="color: #00000080">{{ item.privRealName }}</span>

                    <span style="margin: 0 5px; color: orange" v-if="item.privCheckStatus == 4"
                      >退回给</span
                    >
                    <span style="margin: 0 5px" v-else>转交给</span>
                    <span style="color: #00000080">{{ item.realName }}</span>

                    <!-- <template v-if="item.checkStatus == 4">
                      <span style="color: #00000080">{{ item.realName }}</span>
                      <span style="margin: 0 5px; color: orange">退回给</span>
                      <span style="color: #00000080">{{ item.privRealName }}</span>
                    </template>
                    <template v-else>
                      <span style="color: #00000080">{{ item.privRealName }}</span>
                      <span style="margin: 0 5px">转交给</span>
                      <span style="color: #00000080">{{ item.realName }}</span>
                    </template> -->
                  </div>
                  <div
                    style="
                      background-color: #f7f7fc;
                      padding: 8px;
                      border-bottom-left-radius: 8px;
                      margin-top: 5px;
                    "
                    v-if="item.remark"
                  >
                    {{ item.remark }}
                  </div>
                </template>
                <template v-else-if="item.type == 'reply'">
                  <div
                    style="
                      background-color: #f7f7fc;
                      padding: 8px;
                      border-bottom-left-radius: 8px;
                      margin-top: 5px;
                    "
                  >
                    <div class="flex justify-between gap-2">
                      <div class="flex-1">
                        {{ item.content }}
                      </div>

                      <div>
                        <span class="cursor-pointer mr-2"
                          ><Icon
                            style="color: #ed6f6f"
                            title="删除"
                            icon="ant-design:delete-outlined"
                            v-if="isFlowManager"
                            @click="handleDel(item.id)"
                        /></span>
                        <span
                          class="cursor-pointer"
                          v-if="flowStatus == 1"
                          :style="{ visibility: item.parentId == -1 ? 'visible' : 'hidden' }"
                        >
                          <Icon
                            style="color: #ffc24d"
                            icon="ant-design:message-outlined"
                            @click="handleAddReply(item)"
                          />
                        </span>
                      </div>
                    </div>
                    <template v-if="item.attachments && item.attachments.length">
                      <div v-for="(ela, inAtt) in item.attachments" :key="`att${inAtt}`">
                        <a @click="handleDonwload(ela)">{{ ela.name }}</a>
                        <a @click="handlePreview(ela)" title="预览" v-if="ela.url" class="ml-3"
                          ><EyeOutlined style="color: rgba(28, 106, 235, 1)"
                        /></a>
                      </div>
                    </template>
                  </div>
                  <template v-if="item.aryAnnexSub && item.aryAnnexSub.length">
                    <div
                      style="
                        background-color: #f7f7fc;
                        padding: 8px;
                        border-bottom-left-radius: 8px;
                        margin-top: 5px;
                      "
                      v-for="(el, inAnnex) in item.aryAnnexSub"
                      :key="`annex${inAnnex}`"
                    >
                      <span style="color: #00000080">{{ el.realName }}</span>
                      <span style="margin: 0 5px">回复</span>
                      <span style="color: #00000080">{{ el.replyRealName }}</span>
                      <span style="color: #00000073; margin-left: 8px">{{ el.time }}</span>
                      <div class="flex justify-between gap-2">
                        <div class="flex-1">
                          {{ el.content }}
                        </div>

                        <div>
                          <span class="cursor-pointer mr-2"
                            ><Icon
                              style="color: #ed6f6f"
                              title="删除"
                              icon="ant-design:delete-outlined"
                              v-if="isFlowManager"
                              @click="handleDel(item.id)"
                          /></span>
                        </div>
                      </div>
                      <template v-if="el.attachments && el.attachments.length">
                        <div v-for="(ela, inAtt) in el.attachments" :key="`att${inAtt}`">
                          <a @click="handleDonwload(ela)">{{ ela.name }}</a>
                          <a @click="handlePreview(ela)" title="预览" v-if="ela.url" class="ml-3"
                            ><EyeOutlined style="color: rgba(28, 106, 235, 1)"
                          /></a>
                        </div>
                      </template>
                    </div>
                  </template>
                </template>
                <template v-else-if="item.type == 'sendCopy'">
                  <div
                    style="
                      background-color: #f7f7fc;
                      padding: 8px;
                      border-bottom-left-radius: 8px;
                      margin-top: 5px;
                    "
                    class="flex gap-2"
                  >
                    <div v-for="(csItem, indCs) in item.cs" :key="`cs${indCs}`">
                      <div style="width: 29px; height: 29px; border-radius: 8px; margin: 0 auto">
                        <img
                          v-if="csItem.url"
                          :src="csItem.url"
                          alt=""
                          style="width: 29px; height: 29px; border-radius: 8px"
                        />
                        <template v-else>
                          <img
                            v-if="csItem.gender"
                            :src="womanImg"
                            alt=""
                            style="width: 29px; height: 29px; border-radius: 8px"
                          />
                          <img
                            v-else
                            :src="manImg"
                            alt=""
                            style="width: 29px; height: 29px; border-radius: 8px"
                          />
                        </template>
                      </div>
                      <div style="margin: 5px auto 0">
                        {{ csItem.toRealName }}
                      </div>
                    </div>
                  </div>
                </template>
                <template v-else-if="item.type == 'connector'">
                  <div
                    style="
                      background-color: #f7f7fc;
                      padding: 8px;
                      border-bottom-left-radius: 8px;
                      margin-top: 5px;
                    "
                  >
                    {{ JSON.parse(item.result).code==200?'成功':'失败' }}
                  </div>
                </template>
              </div>
            </div>
          </div>
        </div>
      </TimelineItem>
    </Timeline>
    <ReplyViewModal @register="registerReplyViewModal" @success="fetch" />
  </div>
</template>
<script setup lang="ts">
  import { ref, onMounted, nextTick, computed, h } from 'vue';
  import { ClockCircleOutlined, EyeOutlined } from '@ant-design/icons-vue';
  import { Timeline } from 'ant-design-vue';
  const TimelineItem = Timeline.Item;
  import { dateUtil as dayjs } from '/@/utils/dateUtil';
  import {
    getFlowShow,
    getListAnnex,
    getListDistributeByFlow,
    getListConnectorLog,
    getListDistributeToMe,
    getDelAnnex,
  } from '/@/api/process/process';
  import manImg from '/@/assets/images/man.png';
  import womanImg from '/@/assets/images/woman.png';
  import { useUserStore } from '/@/store/modules/user';
  import { downloadByUrl } from '/@/utils/file/download';
  import Icon from '/@/components/Icon/index';
  import { isArray } from '/@/utils/is';
  import { useMessage } from '/@/hooks/web/useMessage';
  import ReplyViewModal from './ReplyViewModal.vue';
  import { useModal } from '/@/components/Modal';
  const props = defineProps({
    flowId: {
      type: String,
      default: '-1',
    },
    visitKey: {
      type: String,
      default: '',
    },
    moduleCode: {
      type: String, // 来自于哪个模块（因为流程中可能会存在多表单的情况）
      default: '',
    },
    moduleId: {
      type: Number,
      default: -1,
    },
    getFormName: {
      type: String,
      default: '',
    },
    flowInfo: {
      type: Object,
      default: () => {
        return {};
      },
    },
  });
  const { createMessage, createConfirm } = useMessage();

  const userStore = useUserStore();
  const serverInfo = userStore.getServerInfo;
  const list = ref<any>([]); //总列表
  const handleList = ref<any>([]); //处理过程
  const replyList = ref<any>([]); //回复
  const sendCopyList = ref<any>([]); //抄送
  const connectorList = ref<any>([]); //连接器

  const fetch = async () => {
    handleList.value = [];
    replyList.value = [];
    sendCopyList.value = [];
    connectorList.value = [];
    await nextTick();
    const handleRes = await getFlowShow({
      flowId: props.flowId,
      visitKey: props.visitKey,
      cwsFormName: props.getFormName,
      pageType: 'flowShow',
      moduleCode: props.moduleCode,
      moduleId: props.moduleId,
    });
    if (handleRes.aryMyAction && handleRes.aryMyAction.length) {
      handleRes.aryMyAction.forEach((item) => {
        if (item.privMyActionId) {
          const privItem = handleRes.aryMyAction.find((it) => it.id == item.privMyActionId);
          if (privItem) {
            item.privCheckStatus = privItem.checkStatus;
          }
        }

        let showTimes = '';
        if (item.checkDate) {
          const targetDate = dayjs();
          const currentDate = dayjs(item.checkDate);
          // 计算总天数差
          const totalDays = targetDate.diff(currentDate, 'day');
          console.log('totalDays', totalDays);
          if (totalDays <= 3) {
            // 计算剩余的小时差
            const remainingHours = targetDate.subtract(totalDays, 'day').diff(currentDate, 'hour');
            // 计算剩余的分钟差
            const remainingMinutes = targetDate
              .subtract(totalDays, 'day')
              .subtract(remainingHours, 'hour')
              .diff(currentDate, 'minute');
            // 计算剩余的分钟差
            // const remainingSecond = targetDate
            //   .subtract(totalDays, 'day')
            //   .subtract(remainingHours, 'hour')
            //   .subtract(remainingMinutes, 'minute')
            //   .diff(currentDate, 'seconds');
            showTimes = `${totalDays} 天 ${remainingHours} 小时 ${remainingMinutes} 分钟`;
          }
        }
        handleList.value.push({
          ...item,
          type: 'handle',
          title: item.realName,
          time: item.checkDate ? dayjs(item.checkDate).format('YY-MM-DD HH:mm') : '',
          time2: item.checkDate,
          showTimes,
          userPhoto: item.userPhoto
            ? item.userPhoto.startsWith('/')
              ? `${serverInfo.rootPath}${item.userPhoto}`
              : `${serverInfo.rootPath}/${item.userPhoto}`
            : item.userGender
            ? womanImg
            : manImg,
        });
      });
    }
    //没有附件
    // if (handleRes.aryAnnex && handleRes.aryAnnex.length) {
    //   handleRes.aryAnnex.forEach((item) => {
    //     replyList.value.push({
    //       ...item,
    //       type: 'reply',
    //       title: `${item.realName}:${item.content}`,
    //       time: dayjs(item.addDate).format('YY-MM-DD HH:mm'),
    //       aryAnnexSub:
    //         item.aryAnnexSub && item.aryAnnexSub.length
    //           ? item.aryAnnexSub.map((el) => {
    //               return {
    //                 ...el,
    //                 type: 'reply',
    //                 title: `${el.realName} 回复 ${el.replyRealName}:${el.content}`,
    //                 time: dayjs(el.addDate).format('YY-MM-DD HH:mm'),
    //               };
    //             })
    //           : [],
    //     });
    //   });
    // }
    const replyRes = await getListAnnex({ flowId: props.flowId });
    if (replyRes && replyRes.length) {
      replyRes.forEach((item) => {
        replyList.value.push({
          ...item,
          type: 'reply',
          title: `${item.realName}:${item.content}`,
          time: dayjs(item.addDate).format('YY-MM-DD HH:mm'),
          time2: item.addDate,
          aryAnnexSub:
            item.aryAnnexSub && item.aryAnnexSub.length
              ? item.aryAnnexSub.map((el) => {
                  return {
                    ...el,
                    type: 'reply',
                    title: `${el.realName}:${el.content}`,
                    time: dayjs(el.addDate).format('YY-MM-DD HH:mm'),
                    time2: el.addDate,
                    attachments:
                      el.attachments && el.attachments.length
                        ? el.attachments.map((ela) => {
                            const path = ela.visualPath + '/' + ela.diskName;
                            ela.url = path
                              ? serverInfo.rootPath +
                                (path && path.startsWith('/') ? path : `/${path}`)
                              : '';
                            return ela;
                          })
                        : [],
                  };
                })
              : [],
          attachments:
            item.attachments && item.attachments.length
              ? item.attachments.map((el) => {
                  const path = el.visualPath + '/' + el.diskName;
                  el.url = path
                    ? serverInfo.rootPath + (path && path.startsWith('/') ? path : `/${path}`)
                    : '';
                  return el;
                })
              : [],
        });
      });
    }

    const sendCopyRes = await getListDistributeByFlow({
      flowId: props.flowId,
      pageSize: 999,
      op: 'search',
    });
    if (sendCopyRes.list && sendCopyRes.list.length) {
      sendCopyRes.list.forEach((item) => {
        sendCopyList.value.push({
          ...item,
          url: item.photo
            ? serverInfo.rootPath +
              (item.photo && item.photo.startsWith('/') ? item.photo : `/${item.photo}`)
            : '',
          type: 'sendCopy',
          // title: `${item.realName} 抄送给 ${item.toRealName}:${item.title}`,
          time: dayjs(item.disDate).format('YY-MM-DD HH:mm'),
          time2: item.disDate,
        });
      });
    }
    sendCopyList.value = sendCopyList.value.reduce((acc, curr) => {
      const existing = acc.find((item) => item.disDate === curr.disDate);
      if (existing) {
        if (isArray(existing.cs)) {
          existing.cs.push(curr);
        } else {
          existing.cs = [curr];
        }
      } else {
        acc.push({ ...curr, cs: [curr] });
      }
      return acc;
    }, []);

    //连接器
    const connectorRes = await getListConnectorLog({
      flowId: props.flowId,
      pageSize: 999,
      op: 'search',
    });
    if (connectorRes && connectorRes.length) {
      connectorRes.forEach((item) => {
        connectorList.value.push({
          ...item,
          type: 'connector',
          title: `${item.connectorName}`,
          time: dayjs(item.runTime).format('YY-MM-DD HH:mm'),
          time2: item.runTime,
        });
      });
    }

    list.value = [
      ...handleList.value,
      ...replyList.value,
      ...sendCopyList.value,
      ...connectorList.value,
    ].sort((a, b) => {
      const timeA = a.time2 ? new Date(a.time2).getTime() : Infinity; // 无效时间排到最后
      const timeB = b.time2 ? new Date(b.time2).getTime() : Infinity;
      return timeA - timeB;
    });
    console.log('list.value', list.value);
  };
  onMounted(fetch);

  //下载
  const handleDonwload = (record) => {
    if (record.url) {
      downloadByUrl({ url: record.url, fileName: record.name });
    }
  };
  const handlePreview = (record) => {
    if (record.url) {
      const type = record.url.split('.').pop();
      if ('png|PNG|jpg|JPG|jpeg|JPEG|'.includes(type)) {
        window.open(record.url);
      } else if ('doc|DOC|docx|DOCX'.includes(type)) {
        preview('https://view.officeapps.live.com/op/view.aspx?src=' + record.url);
      } else {
        preview(record.url);
      }
    }
  };

  const isFlowManager = computed(() => {
    return props.flowInfo.isFlowManager;
  });

  const flowStatus = computed(() => {
    return props.flowInfo.flowStatus;
  });

  const handleDel = (id: number) => {
    createConfirm({
      iconType: 'warning',
      title: () => h('span', '您确定要删除么？'),
      onOk: async () => {
        await del(id);
      },
    });
  };
  const del = async (id: number) => {
    await getDelAnnex({ id });
    fetch();
  };

  defineExpose({
    fetch,
  });

  //新增回复
  const [registerReplyViewModal, { openModal: openModalReply }] = useModal();

  //新增回复
  const handleAddReply = (record) => {
    openModalReply(true, {
      flowInfo: props.flowInfo,
      record,
    });
  };
</script>
